<template>
    <div>
        <Dropdown>
            <Button type="link" class="add-sampler-btn" my-5> <span text-green>+ 新增脚本取样器</span> </Button>
            <template #overlay>
                <Menu>
                    <Menu.Item>
                        <a href="javascript:;" @click="handleAddConfig('BeanShell')">Bean Shell</a>
                    </Menu.Item>
                    <Menu.Item>
                        <a href="javascript:;" @click="handleAddConfig('JSR223')">JSR223</a>
                    </Menu.Item>
                </Menu>
            </template>
        </Dropdown>
        <StressTestCollapse v-model:dataSource="mergeSamplerList" >
            <template  v-slot="slotProps">
                <StressTestBeanShellForm  v-if="slotProps.dataFromChild.type === 'BeanShell'"  v-model:form-data="slotProps.dataFromChild" />
                <StressTestJSR223Form v-else v-model:form-data="slotProps.dataFromChild"  />
            </template>
            
        </StressTestCollapse>
    </div>
</template>
 
<script lang="ts" setup>
import {
    type IStressCase,
} from '~/types/apis/stress-case'
import {
    Button,
    Dropdown,
    Menu
} from 'ant-design-vue'
import {
    defaultWithIStressCaseBeanShell,
    defaultWithIStressCaseJSR223
} from '~/types/apis/stress-case'

const mergeSamplerList = ref([])


const formModel = defineModel<IStressCase>('formModel', { required: true })
const copyFormModel = {...formModel}
watch(() => copyFormModel, () => {
    formModel.value.beanShell.forEach((element: any) => {
        element.type = 'BeanShell'
    });
    formModel.value.jsr223Sampler.forEach((element: any) => {
        element.type = 'JSR223'
    });
    const list = [...formModel.value.beanShell, ...formModel.value.jsr223Sampler]
    mergeSamplerList.value = list.sort((ar1, ar2) => ar1.sort - ar2.sort) as any

}, {
    deep: true,
    immediate: true,
})

watch(() => mergeSamplerList, () => {
    formModel.value.beanShell = mergeSamplerList.value.map((item: any) => {
        if (item.type === 'BeanShell') {
            const { ['type']: deleted, ...rest } = item;
            return rest
        }
    }).filter((item: any) => typeof item !== 'undefined')

    formModel.value.jsr223Sampler = mergeSamplerList.value.map((item: any) => {
        if (item.type === 'JSR223') {
            const { ['type']: deleted, ...rest } = item;
            return rest
        }
    }).filter((item: any) => typeof item !== 'undefined')
}, {
    deep: true,
})

const handleAddConfig = (type: string) => {
    if (type === 'BeanShell') {
        mergeSamplerList.value.push({ ...defaultWithIStressCaseBeanShell, type, sort:  mergeSamplerList.value.length + 1 })
    } else if (type === 'JSR223') {
        mergeSamplerList.value.push({ ...defaultWithIStressCaseJSR223, type, sort:  mergeSamplerList.value.length + 1 })
    }
}

</script>
 
<style lang="scss" scoped></style>